<template>
	<div class="page-container">
		<h1>正则表达式测试页面</h1>
		<el-form ref="form" :model="form" label-position="top">
			<el-form-item label="正则表达式">
				<el-input v-model="form.pattern"></el-input>
			</el-form-item>
			<el-form-item label="测试字符串">
				<el-input v-model="form.testString"></el-input>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="testRegex">匹配</el-button>
				<el-button @click="resetForm">重置</el-button>
			</el-form-item>
			<el-form-item>
				<p v-if="result">{{ result }}</p>
			</el-form-item>
		</el-form>
		
	</div>
</template>

<script>
	export default {
		data() {
			return {
				form: {
					pattern: '',
					testString: ''
				},
				result: ''
			}
		},

		methods: {
			testRegex() {
				let pattern = this.form.pattern;
				const testString = this.form.testString;
				if (!pattern || !testString) {
					this.$message.error("请输入正则表达式和测试字符串！");
					return;
				};
				
				 // 去掉正则表达式开头的斜杠
				if (pattern.startsWith("/")) {
					pattern = pattern.slice(1);
				};
				// 去掉正则表达式末尾的斜杠
				if (pattern.endsWith("/")) {
					pattern = pattern.slice(0, -1);
				};
				try {
					const regex = new RegExp(pattern);
					this.result = regex.test(testString) ? '匹配成功！' : '匹配失败！';
				} catch (error) {
					this.$message.error("正则表达式格式错误，请检查！");
				}
			},
			resetForm() {
				this.form.pattern = '';
				this.form.testString = '';
				this.result = '';
			}
		}
	}
</script>

<style>

</style>
